package com.bungarus.device.controller;

import com.bungarus.device.model.Device;
import com.bungarus.device.model.DeviceServiceImpl;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/api/device/v1.0/devices")
public class DeviceController extends BungarusController{

    Logger logger = Logger.getLogger(DeviceController.class);

    private DeviceServiceImpl service;

    @Autowired
    public DeviceController(DeviceServiceImpl service) {
        this.service = service;
    }

    @PostMapping
    public ResponseEntity<HashMap<String, Object>> doPostDevices(@RequestParam(name = "tid", required = true) String tid,
                                             @RequestParam(name = "mid", required = true) String mid,
                                             @RequestParam(name = "app", required = true) String app,
                                             @RequestParam(name = "name", required = true) String name,
                                             @RequestParam(name = "type", required = true) int type) {
        Device device = new Device();
        device.setApp(app);
        device.setName(name);
        device.setTenantId(tid);
        device.setMid(mid);
        device.setType(type);
//        int code = DeviceServiceImpl.getInstance().registerDevice(device);
        int code = service.registerDevice(device);
        HashMap<String, Object> response = new HashMap<>();
        response.put("code", code);
        response.put("message", "ok");
        return ResponseEntity.ok()
                .cacheControl(CacheControl.noCache())
                .header("Pragma", "no-cache")
                .body(response);
    }


    @GetMapping
    public ResponseEntity<HashMap<String, Object>> doGetDevices(@RequestParam(name = "app", required = true) String app,
                                                     @RequestParam(name = "tid", required = true) String tid,
                                                     @RequestParam(name = "mid", required = true) String mid) {
//        List<Device> deviceList = DeviceServiceImpl.getInstance().getDeviceList(tid, app, mid);
        List<Device> deviceList = service.getDeviceList(tid, app, mid);
        HashMap<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "ok");
        response.put("data", deviceList);
        return ResponseEntity.ok()
                .cacheControl(CacheControl.noCache())
                .header("Pragma", "no-cache")
                .body(response);
    }

}

